package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

var engine *echo.Echo

func InitEchoFileLoader() *echo.Echo {
	engine = echo.New()
	engine.Use(middleware.Logger())
	engine.Use(middleware.Recover())

	staticPath := GetAbsPath(globalConfig.AttachmentPath)
	engine.Static("/file", staticPath)
	engine.POST("/upload_attachment", upload)
	return engine
}

func UpdateStaticFile() {
	staticPath := GetAbsPath(globalConfig.AttachmentPath)
	engine.Static("/file", staticPath)
}

func upload(c echo.Context) error {
	fmt.Println("hahaha")

	file, err := c.FormFile("file")
	if err != nil {
		return err
	}
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	attachmentpath := GetAbsPath(globalConfig.AttachmentPath)

	// Destination
	dst, err := os.Create(filepath.Join(attachmentpath, file.Filename))
	if err != nil {
		return err
	}
	defer dst.Close()

	// Copy
	if _, err = io.Copy(dst, src); err != nil {
		return err
	}
	return nil
}
